package com.yjd.comm.fraudmetrix.util;

import java.io.IOException;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.yjd.comm.fraudmetrix.model.FraudApiResponse;

public class FraudMetrixServer implements Serializable{

	private static final long serialVersionUID = 1L;
	private final Logger   log    = Logger.getLogger(this.getClass());
    private PoolingClientConnectionManager connMgr;
    private HttpParams                     httpParams;
    private String            apiUrl = "https://api.fraudmetrix.cn/riskService";
    private int maxTotal = 50;
    private int connTimeout = 1000;
    private int soTimeout = 500;
    private Long poolTimeout = 500L;
    private boolean checkEnabled = true;
    private String partner = "yijiedai";
    private String secretKey = "6b57336e04b64dd9ba386c96d24815fa";
    

    public void init() throws Exception {
        // 设置连接池
        connMgr = new PoolingClientConnectionManager(createSchemeRegistry());
        // 设置连接池大小
        connMgr.setMaxTotal(maxTotal);
        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());

        httpParams = new BasicHttpParams();
        // 设置连接超时
        HttpConnectionParams.setConnectionTimeout(httpParams, connTimeout);
        // 设置读取超时
        HttpConnectionParams.setSoTimeout(httpParams, soTimeout);
        // 设置从连接池获取连接实例的超时
        HttpClientParams.setConnectionManagerTimeout(httpParams, poolTimeout);
        // 在提交请求之前 测试连接是否可用
        HttpConnectionParams.setStaleCheckingEnabled(httpParams, checkEnabled);
        
        HttpConnectionParams.setSoKeepalive(httpParams, true);

    }

    public FraudApiResponse invoke(List<NameValuePair> params) throws IOException {
        HttpClient httpClient = new DefaultHttpClient(connMgr, httpParams);
        HttpPost httpPost = new HttpPost(apiUrl);
        HttpResponse response = null;
        HttpEntity entity;
        try {
        	params.add(new BasicNameValuePair("partner_code", partner));
        	params.add(new BasicNameValuePair("secret_key", secretKey));
            httpPost.setEntity(new UrlEncodedFormEntity(params, Charset.forName("utf-8")));
            response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                log.warn("[FraudMetrixServer] invoke failed, response status: " + statusCode);
                return null;
            }
            entity = response.getEntity();
            if (entity == null) {
                log.warn("[FraudMetrixServer] invoke failed, response output is null!");
                return null;
            }
            String result = EntityUtils.toString(entity, "utf-8");
            return JSON.parseObject(result, FraudApiResponse.class);
        } catch (Exception e) {
            log.error("[FraudMetrixServer] invoke throw exception, details: ", e);
            throw e;
        } finally {
            if (response != null) {
                EntityUtils.consume(response.getEntity());
            }
        }
    }

    private SchemeRegistry createSchemeRegistry() {
        SchemeRegistry sr = new SchemeRegistry();
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            sr.register(new Scheme("https", 443, ssf));
        } catch (Exception ex) {
        }
        return sr;
    }

    
	public int getMaxTotal() {
		return maxTotal;
	}

	public void setMaxTotal(int maxTotal) {
		this.maxTotal = maxTotal;
	}

	public String getApiUrl() {
		return apiUrl;
	}

	public void setApiUrl(String apiUrl) {
		this.apiUrl = apiUrl;
	}

	public int getConnTimeout() {
		return connTimeout;
	}

	public void setConnTimeout(int connTimeout) {
		this.connTimeout = connTimeout;
	}

	public int getSoTimeout() {
		return soTimeout;
	}

	public void setSoTimeout(int soTimeout) {
		this.soTimeout = soTimeout;
	}

	public Long getPoolTimeout() {
		return poolTimeout;
	}

	public void setPoolTimeout(Long poolTimeout) {
		this.poolTimeout = poolTimeout;
	}

	public boolean isCheckEnabled() {
		return checkEnabled;
	}

	public void setCheckEnabled(boolean checkEnabled) {
		this.checkEnabled = checkEnabled;
	}

	public String getPartner() {
		return partner;
	}

	public void setPartner(String partner) {
		this.partner = partner;
	}

	public String getSecretKey() {
		return secretKey;
	}

	public void setSecretKey(String secretKey) {
		this.secretKey = secretKey;
	}

    

}
